package com.xiguaji.tiktok.task.blogger.event;

import com.google.common.eventbus.AllowConcurrentEvents;
import com.google.common.eventbus.Subscribe;
import com.gugee.tiktok.common.model.dal.blogger.BloggerLogRepository;
import com.gugee.tiktok.common.model.dal.blogger.BloggerMainRepository;
import com.gugee.tiktok.common.model.dto.SlimBloggerDto;
import com.gugee.tiktok.common.model.mysql.BloggerLog;
import com.xiguaji.boot.eventbus.Event;
import com.xiguaji.boot.eventbus.EventBusTemplate;
import com.xiguaji.boot.eventbus.IEventListener;

import com.xiguaji.tiktok.task.common.job.JobParam;
import com.xiguaji.tiktok.task.core.ScheduleTemplate;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;

import org.springframework.util.CollectionUtils;

@Component
@Slf4j
public class RefreshBloggerMainEventListener implements IEventListener<RefreshBloggerMainEventListener.RefreshBloggerMainEvent> {
    @Autowired
    BloggerLogRepository bloggerLogRepository;

    @Autowired
    BloggerMainRepository bloggerMainRepository;

    @Autowired
    @Lazy
    EventBusTemplate eventBusTemplate;

    @Override
    @Subscribe
    @AllowConcurrentEvents
    public void handle(RefreshBloggerMainEvent event) {
        Thread single= new Thread(()->{run(event);});
        single.start();
        try {
            single.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
            XxlJobLogger.log(e);
        }
    }

    public void run(RefreshBloggerMainEvent event) {
//        XxlJobLogger.log("RefreshBloggerMainEvent:start......");
        int bloggerLogType = BloggerLog.BloggerLogType.REFRESH_BLOGGER_MAIN_LOOP.getValue();

        Optional<BloggerLog> bloggerLogOptional = bloggerLogRepository.findByLogType(bloggerLogType);
        BloggerLog bloggerLog;

        int page = 1;
        if (bloggerLogOptional.isPresent()) {
            page = (int)bloggerLogOptional.get().getCurrentBloggerId();
            bloggerLog = bloggerLogOptional.get();
        } else {
            bloggerLog = new BloggerLog();
            bloggerLog.setLogType(bloggerLogType);
            bloggerLog.setExtValue("");
            bloggerLog.setCreateBy(event.getSource());
            bloggerLog.setUpdateBy(event.getSource());
        }
        long start=System.currentTimeMillis();
        List<SlimBloggerDto> bloggers = bloggerMainRepository.findSlimBloggersScoreAndCount(event.jobParam.getFollowerCounts(),(page-1)* event.jobParam.getCollectLimitCounts(), event.jobParam.getCollectLimitCounts());
        log.info("RefreshBloggerMainEvent:BloggersScoreAndCount {},page={},start={},findSlimBloggersScoreAndCount usetime={}",bloggers.size(),page,(page-1)*event.jobParam.getCollectLimitCounts(),(System.currentTimeMillis()-start)/1000);

        XxlJobLogger.log("RefreshBloggerMainEvent:BloggersScoreAndCount {},page={},start={},findSlimBloggersScoreAndCount usetime={}",bloggers.size(),page,(page-1)*event.jobParam.getCollectLimitCounts(),(System.currentTimeMillis()-start)/1000);

        if (CollectionUtils.isEmpty(bloggers)) {
            bloggerLog.setCurrentBloggerId(1);
            bloggerLogRepository.save(bloggerLog);
            return;
        }

        bloggerLog.setCurrentBloggerId(page+1);
        bloggerLogRepository.save(bloggerLog);
//        long start=System.currentTimeMillis();
//        XxlJobLogger.log("UpdateBloggerMainEvent  start...");
        var saveBloggerEvent = new UpdateBloggerMainEventListener.UpdateBloggerMainEvent(event, bloggers,false);
        eventBusTemplate.post(saveBloggerEvent);
//        XxlJobLogger.log("UpdateBloggerMainEvent  end cost total={}," ,(System.currentTimeMillis()-start)/1000);
    }

    public static class RefreshBloggerMainEvent extends Event {

        public RefreshBloggerMainEvent() {
            super("RefreshBloggerMain");
        }
        public RefreshBloggerMainEvent(JobParam jobParam) {
            super("RefreshBloggerMain");
            this.jobParam=jobParam;
        }
        private  JobParam jobParam;

    }
}
